package com.cityeye.util;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class QueryResult {
	List<Object[]> sucList;
	List<Object[]> failList;

//	qudeptId : List<jiedaoID>
	Map<String, Set<String>> mapQuJiedao = new HashMap<String, Set<String>>();
	Map<String, DeptSummary> mapDeptRow = new HashMap<String, DeptSummary>();

	// "SELECT m1.ASSIGNED_DEPT_ID, m1.ASSIGNED_QUDEPT_ID, count(*) as
	// successnum,SUM(s1.POINT) as winpoints FROM ...
	// 11, 4, 3,22
	public QueryResult(List<Object[]> sucList, List<Object[]> failList) {
		this.sucList = sucList;
		this.failList = failList;
		calResult();
	}

	private void calResult() {
		for(Object[] cols : sucList){
			addSummaryEntry(cols,true);
		}
		
		for(Object[] cols : failList){
			addSummaryEntry(cols,false);
		}
	}
	
	private void addSummaryEntry(Object[] cols, boolean isSuccess){
		String jieDeptId = cols[0].toString();
		String quDeptId = cols[1].toString();
		String count = cols[2].toString();
		String points = cols[3].toString();
		
		DeptSummary jdSummary = getDeptSummary(jieDeptId);
		DeptSummary quSummary = getDeptSummary(quDeptId);		
		
		if(points!=null){
			jdSummary.addPoint(Integer.parseInt(points),isSuccess);
			quSummary.addPoint(Integer.parseInt(points),isSuccess);
		}

		if(count!=null){
			jdSummary.addIssueCount(Integer.parseInt(count),isSuccess);	
			quSummary.addIssueCount(Integer.parseInt(count),isSuccess);	
		}
		
		Set<String> quChildren = getJDSet(quDeptId);
		quChildren.add(jieDeptId);		
	}
	
	public DeptSummary getDeptSummary(String deptId){
		DeptSummary result = mapDeptRow.get(deptId);
		if(result==null)
		{
			result = new DeptSummary(deptId);
			mapDeptRow.put(deptId, result);
		}
		return result;
	}
	
	public Set<String> getQuSet() {
		return mapQuJiedao.keySet();
	}
	
	public Set<String> getJDSet(String quId) {
		Set<String> quChildren = mapQuJiedao.get(quId);
		if(quChildren==null){
			quChildren = new HashSet<String>();
			mapQuJiedao.put(quId, quChildren);
		}		
		return quChildren;
	}
}
